setter 注入

一、注入引用类型

DI 入门案例(XML)

二、注入简单类型

setter 注入

Dao 层

增加简单类型属性,同时提供 setter 方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class BookDaoImpl implements BookDao {
private String type;
private String price;

public void setType(String type) {
this.type = type;
}

public void setPrice(String price) {
this.price = price;
}

@Override
public void save() {
System.out.println("book dao save !!! " + type +": " + price);
}
}

配置

  • 在 bookDao 的 bean 中添加 property
  • name 代表要注入的属性:setter 方法的属性
  • value 代表要注入的值:常量值
1
2
3
4
5
6
7
8
9
10
11
12
13
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

<bean id="bookDao" class="cn.pangcy.dao.impl.BookDaoImpl">
<property name="type" value="架构"/>
<property name="price" value="1000"/>
</bean>
<bean id="bookService" class="cn.pangcy.service.impl.BookServiceImpl">
<property name="bookDao" ref="bookDao" />
</bean>
</beans>

setter 注入
https://blog.pangcy.cn/2023/04/04/后端编程相关/java/spring/setter 注入/
作者
ziYang | 子洋
发布于
2023年4月4日
许可协议